<template>
  <FormItem label="默认值">
    <Cascader v-bind="activeComp.__component__" v-model:value="activeComp.defaultValue" />
  </FormItem>
  <FormItem label="占位提示">
    <Input v-model:value="activeComp.__component__.placeholder" placeholder="请输入占位提示" />
  </FormItem>
  <FormItem label="是否禁用">
    <Switch v-model:checked="activeComp.__component__.disabled" />
  </FormItem>
  <Divider>数据选项</Divider>
  <RadioGroup
    class="!flex justify-center !mb-4"
    v-model:value="activeComp.__data__.type"
    button-style="solid"
  >
    <RadioButton value="static">静态数据</RadioButton>
    <RadioButton value="api">远程数据</RadioButton>
  </RadioGroup>
  <template v-if="activeComp.__data__.type === 'static'">
    <Tree
      :tree-data="activeComp.__component__.options"
      :field-names="fieldNames"
      class="draggable-tree"
      draggable
      block-node
      @drop="onDrop"
    >
      <template #title="{ label, value }">
        <div class="w-[100%] flex justify-between">
          <div>
            {{ label }}
          </div>
          <div class="text-right">
            <Icon
              class="mr-1"
              icon="ant-design:plus-outlined"
              color="#0960bd"
              @click="addChild(value)"
            />
            <Icon icon="ant-design:delete-outlined" color="#f56c6c" @click="delOption(value)" />
          </div>
        </div>
      </template>
    </Tree>
    <Button type="link" @click="addOptions">
      <template #icon>
        <Icon icon="ant-design:plus-circle-outlined" />
      </template>
      添加父级
    </Button>
  </template>
  <template v-if="activeComp.__data__.type === 'api'">
    <div> 未接入远程功能 </div>
  </template>
  <Divider />
  <FormItem label="能否清空">
    <Switch v-model:checked="activeComp.__component__.allowClear" />
  </FormItem>
  <Modal v-model:visible="visible" title="添加选项" @ok="handleOk" @cancel="handleCancel">
    <Form ref="optionFormRef" :model="optionForm" :rules="rules">
      <FormItem label="选项名" name="label">
        <Input v-model:value="optionForm.label" />
      </FormItem>
      <FormItem label="选项值" name="value">
        <Input v-model:value="optionForm.value" />
      </FormItem>
    </Form>
  </Modal>
</template>
<script lang="tsx" setup name="CascaderOption">
  import { ref, reactive, toRefs } from 'vue';
  import {
    Form,
    FormItem,
    Switch,
    Cascader,
    Divider,
    Radio,
    Input,
    Button,
    Tree,
    Modal,
  } from 'ant-design-vue';
  import type { FormInstance } from 'ant-design-vue';
  import type { AntTreeNodeDropEvent, TreeProps } from 'ant-design-vue/es/tree';
  import { cloneDeep } from 'lodash-es';
  import { useFormStore } from '/@/store/modules/workFlow/form';
  import { Icon } from '/@/components/Icon';
  const RadioGroup = Radio.Group;
  const RadioButton = Radio.Button;
  const store = useFormStore();
  const { activeComp } = toRefs<any>(store);
  const visible = ref<boolean>(false);
  const optionFormRef = ref<FormInstance>();
  const childIndex = ref();
  const optionForm = reactive({
    label: '',
    value: '',
  });
  const rules = {
    label: [{ required: true, message: '请输入选项名' }],
    value: [{ required: true, message: '请输入选项值' }],
  };
  const fieldNames: TreeProps['fieldNames'] = {
    title: 'label',
    key: 'value',
    children: 'children',
  };
  /**
   * 拖拽结束触发
   */
  const onDrop = (info: AntTreeNodeDropEvent) => {
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos: any = info.node.pos?.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const loop = (data: TreeProps['treeData'], value: string | number, callback: any) => {
      data?.forEach((item, index) => {
        if (item.value === value) {
          return callback(item, index, data);
        }
        if (item.children) {
          return loop(item.children, value, callback);
        }
      });
    };
    const data = cloneDeep(activeComp.value.__component__.options);
    let dragObj;
    loop(data, dragKey, (item, index: number, arr: any[]) => {
      arr?.splice(index, 1);
      dragObj = item;
    });
    if (!info.dropToGap) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else if ((info.node.children || []).length > 0 && info.node.expanded && dropPosition === 1) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else {
      let ar: TreeProps['treeData'] = [];
      let i = 0;
      loop(data, dropKey, (_item, index: number, arr: TreeProps['treeData']) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }
    activeComp.value.__component__.options = data;
  };
  /**
   * 添加子节点
   * @param index
   */
  const addChild = (index) => {
    childIndex.value = index;
    console.log(index);
    visible.value = true;
  };
  /**
   * 添加选项
   */
  const handleOk = () => {
    const childrenMap = (list, res) => {
      list.map((i) => {
        if (i.value === childIndex.value) {
          i.children.push({
            ...res,
            disabled: false,
            children: [],
          });
        } else {
          childrenMap(i.children, res);
        }
      });
    };
    optionFormRef.value?.validate().then((res) => {
      if (childIndex.value) {
        childrenMap(activeComp.value.__component__.options, res);
      } else {
        activeComp.value.__component__.options.push({
          ...res,
          disabled: false,
          children: [],
        });
      }
      handleCancel();
      visible.value = false;
    });
  };
  /**
   * 添加选项
   */
  const addOptions = () => {
    childIndex.value = null;
    visible.value = true;
  };
  /**
   * 删除选项
   */
  const delOption = (index) => {
    const childrenMap = (list: any[]) => {
      list.map((v, i) => {
        if (v.value === index) {
          list.splice(i, 1);
        } else {
          childrenMap(v.children);
        }
      });
    };
    childrenMap(activeComp.value.__component__.options);
  };
  const handleCancel = () => {
    optionFormRef.value?.resetFields();
  };
</script>
<style lang="less" scoped></style>
